<template>
	<view style="padding: 0 32rpx;">
		<up-navbar :title="formData.store_name" placeholder autoBack></up-navbar>
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<up-form labelPosition="left" labelWidth="75" :model="formData" :rules="rules" ref="formRef">
			<up-form-item label="门店名称" prop="store_name" borderBottom required>
				<up-input v-model="formData.store_name" border="none" placeholder="请填写门店名称"></up-input>
			</up-form-item>
			<up-form-item label="门店简称" prop="store_short_name" borderBottom>
				<up-input v-model="formData.store_short_name" border="none" placeholder="请填写门店简称"></up-input>
			</up-form-item>
			<up-form-item label="联系人" prop="contacts" borderBottom required>
				<up-input v-model="formData.contacts" border="none" placeholder="请填写门店联系人"></up-input>
			</up-form-item>
			<up-form-item label="联系电话" prop="phone" borderBottom required>
				<up-input v-model="formData.phone" border="none" placeholder="请填写门店联系电话"></up-input>
			</up-form-item>
			<up-form-item label="地址" prop="address" borderBottom required @click="setAddress">
				<!-- <up-input v-model="formData.address" border="none" placeholder="点击选择门店地址" readonly type ="textarea" ></up-input> -->
				<view class="">
					{{formData.address}}
				</view>
			</up-form-item>
			<up-form-item label="店面图片" prop="store_img" borderBottom>
				<up-upload :fileList="fileList1" :previewFullImage="true" maxCount="3" @afterRead="addImage"
					@delete="delImage" multiple></up-upload>
			</up-form-item>
		</up-form>
		<up-button @click="submit" type="primary" :loading="submitLoading" :disabled="submitLoading">提交</up-button>
		<up-notify ref="NotifyRef"></up-notify>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive } from 'vue';
	import { onLoad } from '@dcloudio/uni-app'
	import { route } from '@/uni_modules/uview-plus'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { storeEdit } from '@/package_saleman/api/Home'

	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const formData = ref<any>({
		store_name: '',
		store_short_name: '',
		contacts: '',
		phone: '',
		address: '',
		store_img: ''
	})
	const rules = reactive({
		'store_name': {
			type: 'string',
			required: true,
			message: '请填写门店名称',
			trigger: ['blur', 'change'],
		},
		'contacts': {
			type: 'string',
			required: true,
			message: '请填写门店联系人',
			trigger: ['blur', 'change'],
		},
		'phone': {
			type: 'string',
			required: true,
			message: '请填写门店联系电话',
			trigger: ['blur', 'change'],
		},
		'address': {
			type: 'string',
			required: true,
			message: '请填写门店地址',
			trigger: ['blur', 'change'],
		}
	})
	onLoad((options) => {
		const storeInfo = JSON.parse(options.storeInfo)
		formData.value = {
			id: storeInfo.id,
			store_name: storeInfo.store_name,
			store_short_name: storeInfo.store_short_name,
			contacts: storeInfo.contacts,
			phone: storeInfo.phone,
			address: storeInfo.address,
			store_img: storeInfo.store_img,
		}
		fileList1.value = storeInfo.store_img.split(',').filter((url : string) => url !== '').map((url : string) => ({ url }))
	})

	// 使用 ref 创建响应式引用  
	const formRef = ref(null);

	const useUploadImg = () => {
		const fileList1 = ref<any[]>([])

		// 添加图片
		type UploadImageFile = {
			size : number,
			type : 'image',
			url : string,
			thumb : string
		}
		type UploadImageParams = {
			file : UploadImageFile | UploadImageFile[],
			index : number,
			name : string
		}
		type AddImage = (event : UploadImageParams) => any
		// 新增图片
		const addImage = async (event) => {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = fileList1.value.length;
			lists.map((item) => {
				fileList1.value.push({
					...item,
					status: 'uploading',
					message: '上传中',
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadImage(lists[i].url);
				let item = fileList1.value[fileListLen];
				fileList1.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result,
				});
				fileListLen++;
			}
		};

		const uploadImage = (url) => {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: `${process.env.VUE_APP_BASE_URL}/salesman/upload`,
					filePath: url,
					name: 'file',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'token': uni.getStorageSync('trioToken'),
					},
					success: (res) => {
						const data = JSON.parse(res.data)
						if (data.code !== 200) {
							uni.showToast({
								title: `${data.msg},请重新上传!`,
								icon: 'none'
							})
							return
						}
						setTimeout(() => {
							resolve(data.data.url);
						}, 1000);
					},
				});
			});
		};
		// 删除图片
		const delImage = (event : UploadImageParams) => {
			fileList1.value.splice(event.index, 1)
		}

		return {
			fileList1,
			addImage,
			delImage,
			uploadImage
		}
	}
	const { fileList1, addImage, delImage } = useUploadImg()

	// 选择地址
	const setAddress = () => {
		uni.chooseLocation({
			success: (res) => {
				if (res) {
					formData.value.address = `${res.address}${res.name}`
					formData.value.lon = res.longitude
					formData.value.lat = res.latitude
				}
			},
			fail: (err) => {
				console.log(err);
			}
		})
	}

	const submitLoading = ref(false)
	const submit = async () => {
		if (fileList1.value.length > 0) {
			formData.value.store_img = fileList1.value.map((item) => item.url).join(',')
		}
		formRef.value.validate().then(async () => {
			try {
				submitLoading.value = true
				const res = await storeEdit(formData.value)
				showNotify({
					type: 'success',
					message: res.msg,
					top: 0
				})
				formRef.value.resetFields()
				fileList1.value = []
				route({
					type: 'navigateBack'
				})
			} catch (error) {
				showNotify({
					type: 'error',
					message: error.msg,
					top: 0
				})
			} finally {
				submitLoading.value = false
			}
		})

	}
</script>

<style>
</style>